<template>
  <div style="padding: 24px">
    <a-card
      v-for="(question, index) in questions"
      :key="index"
      style="margin-bottom: 24px"
      :title="`题目 ${index + 1}`"
    >
      <div class="question-title">
        {{ question.contentChoice.title }}
      </div>

      <a-radio-group v-model:value="question.userAnswer" @change="() => handleAnswerChange(question)">
        <a-radio
          v-for="(option, optionIndex) in question.contentChoice.options"
          :key="optionIndex"
          :value="String.fromCharCode(65 + optionIndex)"
          style="display: block; margin: 8px 0"
        >
          {{ option }}
        </a-radio>
      </a-radio-group>

      <div v-if="question.userAnswer" style="margin-top: 12px">
        <a-alert
          :message="question.userAnswer === question.answer ? '回答正确' : `回答错误，正确答案是：${question.answer}`"
          :type="question.userAnswer === question.answer ? 'success' : 'error'"
          show-icon
        />
        <a-collapse style="margin-top: 12px">
          <a-collapse-panel key="1" header="答案解析">
            {{ question.analysis }}
          </a-collapse-panel>
        </a-collapse>
      </div>
    </a-card>
  </div>
</template>

<script setup>
import { ref, onMounted, defineEmits, defineExpose } from 'vue'
import { useRoute } from 'vue-router'
import { listQuestions } from "@/api/bizQuesstionController"

const emit = defineEmits(['answer-change'])
const route = useRoute()
const videoID = route.params.videoId
const questions = ref([])

// 暴露给父组件的方法和数据
defineExpose({
  getAnswerStatus,
  getAllQuestions,
  isAllAnswered
})

onMounted(async () => {
  try {
    const res = await listQuestions({ 
      questionType: 1,
      questionTag: videoID,
      page: 1,
      size: 10
    })
    const list = res.data?.data?.records || []

    questions.value = list
      .filter(q => Number(q.questionType) === 1 && q.content)
      .map(q => ({
        ...q,
        contentChoice: JSON.parse(q.content),
        userAnswer: '',
        isCorrect: false
      }))
  } catch (error) {
    console.error('题目加载失败：', error)
  }
})

function handleAnswerChange(question) {
  question.isCorrect = question.userAnswer === question.answer
  emit('answer-change', {
    questionId: question.id,
    isCorrect: question.isCorrect,
    userAnswer: question.userAnswer
  })
}

// 获取所有问题的答题状态
function getAnswerStatus() {
  return questions.value.map(q => ({
    id: q.id,
    isCorrect: q.isCorrect,
    userAnswer: q.userAnswer,
    correctAnswer: q.answer
  }))
}

// 获取所有问题数据
function getAllQuestions() {
  return questions.value
}

// 检查是否所有问题都已回答
function isAllAnswered() {
  return questions.value.every(q => q.userAnswer !== '')
}
</script>

<style scoped>
.question-title {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 10px;
}
</style>